<template>
  <el-menu 
    :default-active="activeIndex" 
    class="cangyuan-sidebar-menu" 
    @select="handleSelect" 
    @open="handleOpen"
    @close="handleClose" 
    :collapse="sidebarCollapsed" 
    background-color="transparent" 
    router 
    text-color="#d4af37"
    active-text-color="#ffd700"
  >
    <!-- 动态渲染菜单项 -->
    <template v-for="menuItem in menuItems" :key="menuItem.Id">
      <!-- 如果有子菜单 -->
      <el-sub-menu v-if="menuItem.children && menuItem.children.length > 0" :index="menuItem.PermissionCode">
        <template #title>
          <el-icon class="cangyuan-menu-icon">
            <component :is="getIconComponent(menuItem.Icon)" />
          </el-icon>
          <span>{{ menuItem.PermissionName }}</span>
        </template>
        
        <!-- 递归渲染子菜单 -->
        <template v-for="subMenu in menuItem.children" :key="subMenu.Id">
          <!-- 子菜单还有子菜单 -->
          <el-sub-menu v-if="subMenu.children && subMenu.children.length > 0" :index="subMenu.PermissionCode">
            <template #title>
              <el-icon class="cangyuan-menu-icon">
                <component :is="getIconComponent(subMenu.Icon)" />
              </el-icon>
              <span>{{ subMenu.PermissionName }}</span>
            </template>
            
            <!-- 递归渲染三级子菜单 -->
            <template v-for="subMenuItem in subMenu.children" :key="subMenuItem.Id">
              <!-- 三级子菜单还有子菜单 -->
              <el-sub-menu v-if="subMenuItem.children && subMenuItem.children.length > 0" :index="subMenuItem.PermissionCode">
                <template #title>
                  <el-icon class="cangyuan-menu-icon">
                    <component :is="getIconComponent(subMenuItem.Icon)" />
                  </el-icon>
                  <span>{{ subMenuItem.PermissionName }}</span>
                </template>
                
                <!-- 四级子菜单项 -->
                <el-menu-item 
                  v-for="fourthItem in subMenuItem.children" 
                  :key="fourthItem.Id"
                  :index="fourthItem.PermissionPath"
                  :class="{ 'active-menu-item': activeIndex === fourthItem.PermissionPath }"
                >
                  <el-icon class="cangyuan-menu-icon">
                    <component :is="getIconComponent(fourthItem.Icon)" />
                  </el-icon>
                  <span>{{ fourthItem.PermissionName }}</span>
                </el-menu-item>
              </el-sub-menu>
              
              <!-- 三级子菜单项 -->
              <el-menu-item 
                v-else
                :key="subMenuItem.Id"
                :index="subMenuItem.PermissionPath"
                :class="{ 'active-menu-item': activeIndex === subMenuItem.PermissionPath }"
              >
                <el-icon class="cangyuan-menu-icon">
                  <component :is="getIconComponent(subMenuItem.Icon)" />
                </el-icon>
                <span>{{ subMenuItem.PermissionName }}</span>
              </el-menu-item>
            </template>
          </el-sub-menu>
          
          <!-- 二级子菜单项 -->
          <el-menu-item 
            v-else
            :key="subMenu.Id"
            :index="subMenu.PermissionPath"
            :class="{ 'active-menu-item': activeIndex === subMenu.PermissionPath }"
          >
            <el-icon class="cangyuan-menu-icon">
              <component :is="getIconComponent(subMenu.Icon)" />
            </el-icon>
            <span>{{ subMenu.PermissionName }}</span>
          </el-menu-item>
        </template>
      </el-sub-menu>
      
      <!-- 单层菜单项 -->
      <el-menu-item 
        v-else
        :index="menuItem.PermissionPath"
        :class="{ 'active-menu-item': activeIndex === menuItem.PermissionPath }"
      >
        <el-icon class="cangyuan-menu-icon">
          <component :is="getIconComponent(menuItem.Icon)" />
        </el-icon>
        <span>{{ menuItem.PermissionName }}</span>
      </el-menu-item>
    </template>
  </el-menu>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getUserMenuPermissions } from '../api/permission'
import {
  Clock,
  House,
  Document,
  Setting,
  Grid,
  Minus,
  User,
  PriceTag,
  CirclePlus,
  Aim,
  Link,
  Warning,
  Bell,
  Shop,
  UserFilled,
  Operation,
  Share,
  CircleClose,
  SwitchButton,
  Avatar,
  DataBoard,
  TrendCharts,
  Monitor,
  Connection,
  Tools,
  Management,
  Star,
  Moon,
  Sunny,
  Cloudy,
  HomeFilled,
  ChatDotRound,
  Finished,
  Tickets,
  Camera
} from '@element-plus/icons-vue'

// Props
interface Props {
  sidebarCollapsed?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  sidebarCollapsed: false
})

// Emits
const emit = defineEmits<{
  select: [key: string]
  open: [key: string, keyPath: string[]]
  close: [key: string, keyPath: string[]]
}>()

// 路由相关
const router = useRouter()
const route = useRoute()

// 响应式数据
const menuItems = ref<any[]>([])
const loading = ref(false)

// 计算属性 - 当前激活的菜单项
const activeIndex = computed(() => {
  return route.path
})

// 图标映射表
const iconMap: Record<string, any> = {
  'Clock': Clock,
  'House': House,
  'Document': Document,
  'Setting': Setting,
  'Grid': Grid,
  'Minus': Minus,
  'User': User,
  'PriceTag': PriceTag,
  'CirclePlus': CirclePlus,
  'Aim': Aim,
  'Link': Link,
  'Warning': Warning,
  'Bell': Bell,
  'Shop': Shop,
  'UserFilled': UserFilled,
  'Operation': Operation,
  'Share': Share,
  'CircleClose': CircleClose,
  'SwitchButton': SwitchButton,
  'Avatar': Avatar,
  'DataBoard': DataBoard,
  'TrendCharts': TrendCharts,
  'Monitor': Monitor,
  'Connection': Connection,
  'Tools': Tools,
  'Management': Management,
  'Star': Star,
  'Moon': Moon,
  'Sunny': Sunny,
  'Cloudy': Cloudy,
  'HomeFilled': HomeFilled,
  'ChatDotRound': ChatDotRound,
  'Finished': Finished,
  'Tickets': Tickets,
  'Camera': Camera
}

/**
 * 获取图标组件
 * @param iconName 图标名称
 * @returns 图标组件
 */
const getIconComponent = (iconName: string) => {
  return iconMap[iconName] || Document
}

/**
 * 处理菜单选择
 * @param key 选中的菜单key
 */
const handleSelect = (key: string) => {
  emit('select', key)
  console.log('选择菜单:', key)
}

/**
 * 处理菜单展开
 * @param key 展开的菜单key
 * @param keyPath 菜单路径
 */
const handleOpen = (key: string, keyPath: string[]) => {
  emit('open', key, keyPath)
  console.log('展开菜单:', key, keyPath)
}

/**
 * 处理菜单收起
 * @param key 收起的菜单key
 * @param keyPath 菜单路径
 */
const handleClose = (key: string, keyPath: string[]) => {
  emit('close', key, keyPath)
  console.log('收起菜单:', key, keyPath)
}

/**
 * 获取用户菜单权限
 */
const fetchMenuPermissions = async () => {
  loading.value = true
  try {
    const response = await getUserMenuPermissions()
    
    if (response.data.code === 200) {
      const rawData = response.data.data || []
      
      // 递归处理菜单数据，确保字段名统一
      const processMenuData = (items: any[]): any[] => {
        return items.map((item: any) => {
          const processedItem = {
            ...item,
            // 确保字段名统一
            Id: item.Id || item.id,
            PermissionName: item.PermissionName || item.permissionName,
            PermissionCode: item.PermissionCode || item.permissionCode,
            PermissionPath: item.PermissionPath || item.permissionPath,
            PermissionType: item.PermissionType || item.permissionType,
            Icon: item.Icon || item.icon,
            ParentId: item.ParentId || item.parentId,
            Level: item.Level || item.level,
            SortOrder: item.SortOrder || item.sortOrder,
            // 递归处理子菜单
            children: []
          }
          
          // 处理子菜单 - 支持 Children 和 children 两种字段名
          const children = item.Children || item.children || []
          if (children && children.length > 0) {
            processedItem.children = processMenuData(children)
          }
          
          return processedItem
        })
      }
      
      const processedData = processMenuData(rawData)
      console.log('原始菜单数据:', rawData)
      console.log('处理后的菜单数据:', processedData)
      
      // 检查是否有子菜单
      processedData.forEach((item, index) => {
        console.log(`菜单项 ${index}:`, {
          name: item.PermissionName,
          children: item.children,
          childrenLength: item.children?.length || 0
        })
      })
      
      menuItems.value = processedData
    } else {
      ElMessage.error('获取菜单权限失败')
    }
  } catch (error) {
    console.error('获取菜单权限失败:', error)
    ElMessage.error('获取菜单权限失败')
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  fetchMenuPermissions()
})

// 暴露方法给父组件
defineExpose({
  refreshMenu: fetchMenuPermissions
})
</script>

<style scoped>
.cangyuan-sidebar-menu {
  border: none;
}

.cangyuan-menu-icon {
  margin-right: 8px;
  font-size: 16px;
}

.active-menu-item {
  background-color: rgba(255, 215, 0, 0.1) !important;
}

.el-menu-item:hover {
  background-color: rgba(255, 215, 0, 0.05) !important;
}

.el-sub-menu .el-menu-item:hover {
  background-color: rgba(255, 215, 0, 0.05) !important;
}
</style>
